﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EngineOfEvermore.Editor.Common.Command
{
    class CommandManager : IDisposable
    {
        #region class CommandEntry
        class CommandEntry
        {
            public ICommand Command;
            public int Version;
        }
        #endregion


        #region Variables
        bool _disposed = false;
        List<CommandEntry> _commandStack = new List<CommandEntry>();
        int _commandIndex = -1;
        int _maxVersion = -1;
        #endregion

        #region Finalizer
        ~CommandManager()
        {
            Dispose( false );
        }
        #endregion

        #region Properties
        public bool CanUndo
        {
            get
            {
                return _commandStack.Any() && _commandIndex >= 0;
            }
        }

        public bool CanRedo
        {
            get
            {
                bool isLastAction = ( _commandIndex == _commandStack.Count - 1 );
                return !isLastAction && _commandStack.Any();
            }
        }

        public int Version
        {
            get
            {
                if ( _commandIndex >= 0 && _commandIndex < _commandStack.Count )
                {
                    return _commandStack[_commandIndex].Version;
                }
                else
                {
                    return -1;
                }
            }
        }
        #endregion

        #region Methods
        public void Undo()
        {
            if ( !CanUndo )
                return;

            Debug.Assert( _commandIndex >= 0 );
            Debug.Assert( _commandIndex < _commandStack.Count );

            // Take one command from the list
            ICommand command = _commandStack[_commandIndex--].Command;

            command.Undo();
        }

        public void Redo()
        {
            if ( !CanRedo )
                return;

            Debug.Assert( _commandIndex >= -1 );
            Debug.Assert( _commandIndex < _commandStack.Count - 1 );

            // Take next command in the list
            ICommand command = _commandStack[++_commandIndex].Command;

            command.Execute();
        }

        public void AddUndoAction( ICommand command )
        {
            Debug.Assert( command != null );

            // If the _commandIndex is not at the end of the
            // list remove anything after it
            Truncate();

            CommandEntry entry = new CommandEntry();
            entry.Command = command;
            entry.Version = ++_maxVersion;

            _commandStack.Add( entry );
            ++_commandIndex;
        }

        public void Truncate()
        {
            if ( _commandIndex != _commandStack.Count - 1 )
            {
                for ( int i = _commandIndex + 1; i < _commandStack.Count; ++i )
                {
                    IDisposable disposable =
                        ( _commandStack[i].Command as IDisposable );

                    if ( disposable != null )
                    {
                        disposable.Dispose();
                    }
                }

                _commandStack.RemoveRange(
                    _commandIndex + 1,
                    _commandStack.Count - ( _commandIndex + 1 )
                    );
            }
        }
        #endregion

        #region IDisposable Members

        protected virtual void Dispose( bool disposing )
        {
            if ( !_disposed )
            {
                if ( disposing )
                {
                    foreach ( IDisposable disposable in
                        _commandStack.Select( x => x.Command ).OfType<IDisposable>() )
                    {
                        if ( disposable != null )
                        {
                            disposable.Dispose();
                        }
                    }

                    _commandStack.Clear();
                    _commandStack = null;
                }

                _disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose( true );

            GC.SuppressFinalize( this );
        }

        #endregion
    }
}
